package org.garbagecan.springstudy.dao.hibernate;

import java.util.List;

import org.garbagecan.springstudy.dao.hibernate.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	
	public static void main(String[] args) throws Exception {
		test1();
		test2();
		test3();
		testCache();
	}
	private static void test1() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
			"/org/garbagecan/springstudy/dao/hibernate/spring1.xml");
		test((UserService) ctx.getBean("userService"));
	}

	private static void test2() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"/org/garbagecan/springstudy/dao/hibernate/spring2.xml");
		test((UserService) ctx.getBean("userService"));
	}

	private static void test3() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"/org/garbagecan/springstudy/dao/hibernate/spring3.xml");
		test((UserService) ctx.getBean("userService"));
	}

	private static void testCache() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"/org/garbagecan/springstudy/dao/hibernate/spring-cache.xml");
		UserService userService = (UserService) ctx.getBean("userService");
		UserService cachedUserService = (UserService) ctx.getBean("cachedUserService");
		for (int i = 0; i < 10; i++) {
			User user = new User();
			user.setId("" + System.currentTimeMillis() + i);
			user.setName("name_" + System.currentTimeMillis() + i);
			user.setPassword("password_" + i);
			cachedUserService.add(user);
		}
		System.out.println(cachedUserService.list());

		List<User> users = userService.list();
		for (User user : users) {
			user.setPassword("123456");
			userService.update(user);
		}
		System.out.println(cachedUserService.list());

		for (User user : users) {
			user.setPassword("123456");
			cachedUserService.update(user);
		}
		System.out.println(cachedUserService.list());

	}

	private static void test(UserService userService) {
		for (int i = 0; i < 10; i++) {
			User user = new User();
			user.setId("" + System.currentTimeMillis() + i);
			user.setName("name_" + System.currentTimeMillis() + i);
			user.setPassword("password_" + i);
			userService.add(user);

			User user1 = userService.findById(user.getId());
			System.out.println("user1: " + user1);

			user1.setPassword("123456");
			userService.update(user1);
			User user2 = userService.findById(user.getId());
			System.out.println("user2: " + user2);
		}

		List<User> users = userService.list();
		System.out.println(users);
		for (User user : users) {
			//userService.delete(user);
		}
		users = userService.list();
		System.out.println(users);
	}
}
